const noble = require('@abandonware/noble');
const EventEmitter = require('events');

class BluetoothService extends EventEmitter {
  constructor() {
    super();
    this.peripheral = null;
    this.characteristic = null;
    this.isConnected = false;
    this.scanTimeout = null;
    this.discoveredDevices = new Map();
    
    // 按摩椅设备特征
    this.MASSAGE_CHAIR_SERVICE_UUID = 'fff0'; // 根据实际设备修改
    this.MASSAGE_CHAIR_CHARACTERISTIC_UUID = 'fff1'; // 根据实际设备修改
    
    this.initializeBluetooth();
  }

  initializeBluetooth() {
    noble.on('stateChange', (state) => {
      console.log('蓝牙状态变化:', state);
      if (state === 'poweredOn') {
        console.log('蓝牙已开启，准备扫描设备');
      } else {
        console.log('蓝牙未开启');
        noble.stopScanning();
      }
    });

    noble.on('discover', (peripheral) => {
      this.handleDeviceDiscovered(peripheral);
    });
  }

  handleDeviceDiscovered(peripheral) {
    const deviceInfo = {
      id: peripheral.id,
      name: peripheral.advertisement.localName || '未知设备',
      rssi: peripheral.rssi,
      services: peripheral.advertisement.serviceUuids || [],
      peripheral: peripheral
    };

    // 检查是否是按摩椅设备（根据设备名称或服务UUID）
    const isMassageChair = this.isMassageChairDevice(deviceInfo);
    
    if (isMassageChair) {
      console.log('发现按摩椅设备:', deviceInfo.name, deviceInfo.id);
      this.discoveredDevices.set(peripheral.id, deviceInfo);
      this.emit('deviceDiscovered', deviceInfo);
    }
  }

  isMassageChairDevice(deviceInfo) {
    // 根据设备名称判断（需要根据实际设备修改）
    const massageChairNames = ['按摩椅', 'MassageChair', 'MASSAGE'];
    const nameMatch = massageChairNames.some(name => 
      deviceInfo.name.toLowerCase().includes(name.toLowerCase())
    );

    // 根据服务UUID判断
    const serviceMatch = deviceInfo.services.includes(this.MASSAGE_CHAIR_SERVICE_UUID);

    return nameMatch || serviceMatch;
  }

  async startScanning(timeout = 10000) {
    return new Promise((resolve, reject) => {
      try {
        if (noble.state !== 'poweredOn') {
          reject(new Error('蓝牙未开启'));
          return;
        }

        this.discoveredDevices.clear();
        console.log('开始扫描按摩椅设备...');
        
        noble.startScanning();

        this.scanTimeout = setTimeout(() => {
          noble.stopScanning();
          const devices = Array.from(this.discoveredDevices.values()).map(device => ({
            id: device.id,
            name: device.name,
            rssi: device.rssi
          }));
          
          console.log(`扫描完成，发现 ${devices.length} 个按摩椅设备`);
          resolve(devices);
        }, timeout);

      } catch (error) {
        reject(new Error(`扫描失败: ${error.message}`));
      }
    });
  }

  async connectToDevice(deviceId) {
    return new Promise((resolve, reject) => {
      try {
        const deviceInfo = this.discoveredDevices.get(deviceId);
        if (!deviceInfo) {
          reject(new Error('设备未找到'));
          return;
        }

        const peripheral = deviceInfo.peripheral;
        console.log('连接设备:', deviceInfo.name);

        peripheral.connect((error) => {
          if (error) {
            reject(new Error(`连接失败: ${error.message}`));
            return;
          }

          console.log('设备连接成功，正在发现服务...');
          peripheral.discoverServices([this.MASSAGE_CHAIR_SERVICE_UUID], (error, services) => {
            if (error) {
              reject(new Error(`发现服务失败: ${error.message}`));
              return;
            }

            if (services.length === 0) {
              reject(new Error('未找到按摩椅服务'));
              return;
            }

            const service = services[0];
            service.discoverCharacteristics([this.MASSAGE_CHAIR_CHARACTERISTIC_UUID], (error, characteristics) => {
              if (error) {
                reject(new Error(`发现特征失败: ${error.message}`));
                return;
              }

              if (characteristics.length === 0) {
                reject(new Error('未找到按摩椅特征'));
                return;
              }

              this.peripheral = peripheral;
              this.characteristic = characteristics[0];
              this.isConnected = true;

              // 设置断开连接处理
              peripheral.on('disconnect', () => {
                console.log('设备已断开连接');
                this.isConnected = false;
                this.peripheral = null;
                this.characteristic = null;
                this.emit('connectionStateChanged', 'disconnected');
              });

              // 启用数据接收通知
              this.characteristic.on('data', (data) => {
                console.log('接收到数据:', data.toString('hex'));
                this.emit('dataReceived', data);
              });

              this.characteristic.subscribe((error) => {
                if (error) {
                  console.error('启用通知失败:', error);
                } else {
                  console.log('数据通知已启用');
                }
              });

              console.log('按摩椅设备连接并配置完成');
              this.emit('connectionStateChanged', 'connected');
              resolve(true);
            });
          });
        });

      } catch (error) {
        reject(new Error(`连接过程出错: ${error.message}`));
      }
    });
  }

  async disconnect() {
    return new Promise((resolve, reject) => {
      try {
        if (!this.isConnected || !this.peripheral) {
          resolve();
          return;
        }

        this.peripheral.disconnect((error) => {
          if (error) {
            reject(new Error(`断开连接失败: ${error.message}`));
          } else {
            console.log('设备断开连接成功');
            resolve();
          }
        });

      } catch (error) {
        reject(new Error(`断开连接过程出错: ${error.message}`));
      }
    });
  }

  async sendCommand(commandBuffer) {
    return new Promise((resolve, reject) => {
      try {
        if (!this.isConnected || !this.characteristic) {
          reject(new Error('设备未连接'));
          return;
        }

        console.log('发送指令:', commandBuffer.toString('hex'));
        
        this.characteristic.write(commandBuffer, false, (error) => {
          if (error) {
            reject(new Error(`发送指令失败: ${error.message}`));
          } else {
            console.log('指令发送成功');
            resolve(true);
          }
        });

      } catch (error) {
        reject(new Error(`发送指令过程出错: ${error.message}`));
      }
    });
  }

  async getStatus() {
    // 这里可以发送查询状态的指令，然后等待返回数据
    // 暂时返回模拟数据
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(Buffer.from([0x59, 0x57, 0x01, 0x00, 0x00])); // 模拟状态数据
      }, 100);
    });
  }

  isDeviceConnected() {
    return this.isConnected;
  }
}

module.exports = BluetoothService;